package org.shoukaiseki.randomtoolsweb.data;


import com.alibaba.druid.pool.DruidDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.lang3.RandomUtils;
import org.shoukaiseki.randomtools.utils.RandomChineseName;
import org.shoukaiseki.randomtools.utils.RandomInteger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * org.shoukaiseki.randomtoolsweb.data.UserServiceImpl <br>
 *
 * @author 蒋カイセキ    Japan-Tokyo  2018-08-20 22:25:26<br>
 * ブログ http://shoukaiseki.blog.163.com/<br>
 * E-メール jiang28555@Gmail.com<br>
 **/

@Service
public class UserServiceImpl implements UserService{

    static Logger  logger= LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private DataSource dataSource;

    public UserServiceImpl(){

    }

    @Override
    public int saveRandom(int length) {
        try {
            Connection conn = dataSource.getConnection();
            conn.setAutoCommit(false);
            QueryRunner qr = new QueryRunner(dataSource);
            String sql = "insert into testuser(name, boo) values(?,?)";
            String sql2 = "insert into testuser2(name, b1,b2,b3,b4,b5,b6,b7,b8) values(?,?,?,?,?,?,?,?,?)";
            PreparedStatement ps = conn.prepareStatement(sql);
            PreparedStatement ps2 = conn.prepareStatement(sql2);

            boolean needBatch=false;
            for (int i = 1; i < length+1; i++) {
                String name = RandomChineseName.randomChineseName();
                Integer boo= RandomInteger.randomInt(0,255);
                ps.setObject(1,name);
                ps.setObject(2,boo);
                ps.addBatch();

                ps2.setObject(1,name);
                ps2.setBoolean(2,(boo&1)>0);
                ps2.setBoolean(3,(boo&2)>0);
                ps2.setBoolean(4,(boo&4)>0);
                ps2.setBoolean(5,(boo&8)>0);
                ps2.setBoolean(6,(boo&16)>0);
                ps2.setBoolean(7,(boo&32)>0);
                ps2.setBoolean(8,(boo&64)>0);
                ps2.setBoolean(9,(boo&128)>0);
                ps2.addBatch();

                needBatch=true;
                if((i%5000==0)){
                    ps.executeBatch();
                    ps2.executeBatch();
                    needBatch=false;
                }
            }

            if(needBatch){
                ps.executeBatch();
                ps2.executeBatch();
            }

            conn.commit();


        } catch (Exception e) {
            e.printStackTrace();
        }

        return 0;
    }
}
